//
//  ALPictureViewCell.swift
//  ALSinaWeiBoSwift
//
//  Created by 柴瑞军 on 16/4/15.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit
import SDWebImage
//collectionViewCell的间距
//如果某些属性或者变量只需要计算一次:
//那么方式有两种:
//1.在模型中的属性监测器中设置
//2.定义全局的常量进行赋值
private let ALStautsPictureViewCellMargin: CGFloat = 4
private let identifier = "identifier"

// cell 的最大列数是3,列数使用整数
private let ALStatusPictureViewMaxColumn = 3

//计算cell的宽和高
private let AlStatusPictureViewItemWH = (UIScreen.mainScreen().bounds.width-2*ALIconViewMargin-(CGFloat(ALStatusPictureViewMaxColumn)-1)*ALStautsPictureViewCellMargin)/CGFloat(ALStatusPictureViewMaxColumn)
class ALPictureView: UICollectionView {
    private let layout = UICollectionViewFlowLayout()
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    init(){
    super.init(frame: CGRectZero, collectionViewLayout: layout)
        backgroundColor = UIColor.clearColor()
        
        self.dataSource = self
        
//        注册cell
        registerClass(ALStatusPictureViewCell.self, forCellWithReuseIdentifier: identifier)
    }
    //配图的数组
    var pictureURLs:[NSURL]? {
        didSet{
        //当别人设置图片的url后我们就计算每个cell的大小
            let size = cellSize()
            
            //自己来约束大小,当cell给pictureURLs之后计算出宽高,然后重新修改约束
            self.snp_updateConstraints { (make) in
                make.size.equalTo(size)
                
                
//                刷新tableView
                reloadData()
            }
        }
    }
    
    
    
    //计算cell的大小
    private func cellSize() -> CGSize{
    
        //设置collectionView layout
        layout.itemSize = CGSize(width: AlStatusPictureViewItemWH, height: AlStatusPictureViewItemWH)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
//        判断图片的数量
        let count = pictureURLs?.count ?? 0
        
        
        if  count == 0 {
//            ALPrint("没有图片")
            return CGSizeZero
        }
        
        //一张图片
        if count == 1 {
//TODO: - 返回图片本来的大小
            
            
//            设置图片的默认的大小
            var size = CGSize(width: AlStatusPictureViewItemWH, height: AlStatusPictureViewItemWH)
//            //先取出单张图片对应的url
            let url = pictureURLs?.first
            //在缓存中通过SDImageCache取出缓存的图片,可能取到,也有可能取不到
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url?.absoluteString){
            size = image.size
//                由于得到的图片的大小的单位是像素,我们要计算的是在retain频幕下要展示的图片的大小,所以要对其进行转换,在retain屏幕下的缩放比例是scale = 2    点 = 像素 * 2  retain屏幕小描述图片的单位是点
                size = CGSize(width: size.width*(UIScreen.mainScreen().scale), height: size.height*(UIScreen.mainScreen().scale))
                
            }
            //如果图片太大或者太小都需要处理一下
            if size.width < 40 {
                size.width = 40
            }
            if size.width > UIScreen.mainScreen().bounds.width*0.5{
                size.width = UIScreen.mainScreen().bounds.width*0.5
            }
            
            layout.itemSize = size
            return size
        }
        layout.minimumInteritemSpacing = ALStautsPictureViewCellMargin
        layout.minimumLineSpacing = ALStautsPictureViewCellMargin
//        多张图片,列数不确定
//        2张和4张显示2列,其他的都显示3列
        var column = ALStatusPictureViewMaxColumn
        if count == 2 || count == 4 {
            column = 2
        }
        // 服务器开发用得比较多,分页,保证列数是整数
//        行数的计算
//        行数 = (总个数 + 列数 - 1) / 列数
        let row = (count + column - 1)/column
//        计算宽度和高度
        
        let width = CGFloat(column)*AlStatusPictureViewItemWH+(CGFloat(column)-1)*ALStautsPictureViewCellMargin
        
//        计算高度
        let height = CGFloat(row)*AlStatusPictureViewItemWH+(CGFloat(row)-1)*ALStautsPictureViewCellMargin
        
        return CGSize(width: width, height: height)
    }
    
}
extension ALPictureView:UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! ALStatusPictureViewCell
        cell.imageURL = pictureURLs?[indexPath.item]
        
        return cell
    }
}

class ALStatusPictureViewCell:UICollectionViewCell{

    //定义一个设置图片数组中的URl
    var imageURL:NSURL?{
        didSet{
            bgImageView.sd_setImageWithURL(imageURL)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加控件
        preparaUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func preparaUI(){
//    添加在控件
        contentView.addSubview(bgImageView)
//        添加约束
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
    }
    //定义一个用来展示图片的uiimageView
    private lazy var bgImageView:UIImageView = {
    let image = UIImageView()
        
//        设置uiimegeview的contentMode
        image.contentMode = UIViewContentMode.ScaleAspectFill
        
//        设置imageview的clipToBounds
        image.clipsToBounds = true
    
        return image
    }()
}